<?php
class logs{
  const DEBUG = 0;
  const ERROR = 1;
  const WARN  = 2;
  const INFO  = 3;
  protected $logFileHandler = null;
  protected $logFilePath;
  protected $logFileName='';
  public $date_format='Y-m-d H:i:s';
  private $writeLogAtEnd=true;
  private static $logHash =array();
  private $postfix='log';
  public function init($params=array()){
	$this->logFilePath=$this->yum->vars('sys','root').$params['log'];
	$this->postfix=$params['postfix'];
  }
  public function Logname($name,$writeLogAtEnd=false){
  	$this->writeLogAtEnd=$writeLogAtEnd;
  	$this->logFileName=$name.'.'.$this->postfix;
  	$this->openFile();
    if ($this->writeLogAtEnd===true){
      $this->closeFile();
    }
  }
  private function openFile(){
    if ($this->logFileHandler){
      return true;
    }
    $fileName=$this->logFilePath.$this->logFileName;
    $this->logFileHandler=fopen($fileName,'a+');
    if (!$this->logFileHandler){
      $this->yum->error('Logger :: Cannot open file on path: ' . $fileName);
    }
  }
  private function closeFile() {
    @fclose($this->logFileHandler);
    $this->logFileHandler = null;
  }
  public function log($message,$severity=self::INFO){
    $log = $this->prepareLog($message, $severity);
    self::$logHash[] = $log;
    if ($this->writeLogAtEnd===false){
      $this->writeLog();
    }
  }
  private function getSeverityNiceName($severity){
	$names = array (self::DEBUG   => "Debug",
                    self::ERROR   => "Error",
                    self::WARN => "Warning",
                    self::INFO    => "Info"
                   );
    if(array_key_exists($severity, $names)){
      return $names[$severity];
    }else{
      return "Invalid Severity {$severity}";
    }
  }
  protected function prepareLog($message,$severity){
    return date($this->date_format).' '.$this->getSeverityNiceName($severity).': '.$message;
  }
  public function writeLog(){
    if(empty(self::$logHash)){
      return false;
    }
    $this->openFile();
    $text = implode("\n", self::$logHash);
    if(fwrite($this->logFileHandler, $text . "\n")==false){
      $this->yum->error('Logger :: Unable to write to log file.');
    }
    self::$logHash = array();
  }
  public function __destructor(){
    $this->writeLog();
    @fclose($this->logFileHandler);
  }
}
?>